import os.path
import sys
from string import *
import time
#from MultiGenSqueeze import *
from GenSqueezeFast import *

def openSequence(filename):
    if os.path.exists(filename):
        return open(filename)
    else:
        print "Cannot open file '" + filename + "'"
        exit(1)

def main():
    chunksize = int(sys.argv[2])
    ratio = float(sys.argv[3])
    filelist = open(sys.argv[1])
    outFile = open("distancematrix.phy", "w")
    names = []
    uglyNames = []
    seqs = []
    count = 0

    for name in filelist:
        stripped = name.strip()
        if (stripped):
            lastSlash = stripped.rfind('/')
            ugly = ((stripped[lastSlash+1:lastSlash+10])+"         ")[:9]
            uglyNames.append(ugly)
            names.append(stripped)
            seqs.append(open(stripped).read())
            count += 1
    
    print >> outFile, count
    print "starting test"
    tstart = time.time()
    for i in range(count):
        line = uglyNames[i]
        for j in range(count):
            if i == j:
                line += ' %0.7f' % (0.0)
                continue
            u = seqs[j]
            v = seqs[i]
            GSu = GenSqueeze(u, chunksize)
            GSu.compress(ratio)
            uLen = len("".join(GSu.encoded))
            GSuGv = GenSqueeze(u, chunksize, v)
            GSuGv.compress(ratio)
            uGvLen = len("".join(GSuGv.encoded))
            GSuv = GenSqueeze(u+v, chunksize)
            GSuv.compress(ratio)
            uvLen = len("".join(GSuv.encoded))
            d = 1.0 - float(uLen - uGvLen) / uvLen
            line += " %0.7f" % (d)
            print "Done comparison" + str(i) + "," + str(j)
        print "Done row " + str(i)
        print >> outFile, line 
    tend = time.time()
    print 'time: %0.3f ms' % ((tend-tstart)*1000.0) 
main()
